package com.basic.auth.service.impl;


import com.basic.auth.dao.mapper.AuthFuncMapper;
import com.basic.auth.dao.mapper.AuthUserFuncExMapper;
import com.basic.auth.dao.mapper.AuthUserFuncMapper;
import com.basic.auth.dao.model.AuthFunc;
import com.basic.auth.dao.model.AuthFuncExample;
import com.basic.auth.dao.model.AuthUserFunc;
import com.basic.auth.dao.model.AuthUserFuncExample;
import com.basic.auth.domain.AuthFuncBo;
import com.basic.auth.domain.AuthUserFuncBo;
import com.basic.auth.service.AuthFuncService;
import com.basic.auth.service.AuthUserFuncService;
import com.basic.common.bean.BeanCopierDsUtil;
import com.basic.common.constant.CommonDsConstant;
import com.basic.common.string.StringCheckDsUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户功能管理
 *
 * @author 
 * @version 1.0
 * @Date 8/14 19:22
 */
@Service
public class AuthUserFuncServiceImpl implements AuthUserFuncService {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private AuthUserFuncMapper authUserFuncMapper;
    @Resource
    private AuthUserFuncExMapper authUserFuncExMapper;
    @Resource
    private AuthFuncMapper authFuncMapper;
    @Resource
    private AuthFuncService authFuncService;
//    @Autowired
//    private MemberInfoService memberInfoService;

//    public List<AuthUserFuncBo> selAuthShopNameListByParam(AuthUserFuncBo userFuncBo) {
//        List<Long> boIdlist = selAuthBoIdListByParam(userFuncBo);
//        if (CollectionUtils.isEmpty(boIdlist)) {
//            return null;
//        }
//
//        return null;
//    }
//    public List<AuthUserFuncBo> selAuthMemberNameListByParam(AuthUserFuncBo userFuncBo) {
//        List<Long> boIdlist = selAuthBoIdListByParam(userFuncBo);
//        if (CollectionUtils.isEmpty(boIdlist)) {
//            return null;
//        }
//        MemberInfoBo memberInfoBo = new MemberInfoBo();
//        memberInfoBo.setBoIdList(boIdlist);
//        List<MemberInfo> memberInfoList = memberInfoService.selMemberInfoListByParam(memberInfoBo);
//        if (CollectionUtils.isEmpty(memberInfoList)) {
//            return null;
//        }
//        Map<Long, MemberInfo> goodsInfoBoMap = memberInfoList.stream().collect(Collectors.toMap(MemberInfo::getBoId, a -> a, (k1, k2) -> k1));
//        List<AuthUserFuncBo> funcBoArrayList = new ArrayList<>();
//        for (Long boId : boIdlist) {
//            AuthUserFuncBo authUserFuncBo = new AuthUserFuncBo();
//            authUserFuncBo.setBoId(boId);
//            authUserFuncBo.setAuthName(goodsInfoBoMap.get(boId).getRealName());
//            funcBoArrayList.add(authUserFuncBo);
//        }
//        return funcBoArrayList;
//    }


    /**
     * 条件查询授权人boId
     *
     * @param userFuncBo
     * @return java.util.List<java.lang.Long>
     * @author 
     * @date 13:50 2019/8/21
     */
    @Override
    public List<String> selAuthBoIdListByParam(AuthUserFuncBo userFuncBo) {
        if(userFuncBo == null || userFuncBo.getSystemId() == null || userFuncBo.getParentFuncId() == null
            || userFuncBo.getBoId() == null){
            return null;
        }
        AuthFuncBo funcBo = new AuthFuncBo();
        funcBo.setSystemId(userFuncBo.getSystemId());
        funcBo.setAxisLike("$" + userFuncBo.getParentFuncId());

        List<AuthFunc> authFuncList = authFuncService.selFuncListByParam(funcBo);
        if (CollectionUtils.isEmpty(authFuncList)) {
            return null;
        }
        List<Long> idList = authFuncList.stream().map(a -> a.getId()).collect(Collectors.toList());
        AuthUserFuncBo funcBoParam = new AuthUserFuncBo();
        funcBoParam.setSystemId(userFuncBo.getSystemId());
        funcBoParam.setBoId(userFuncBo.getBoId());
        funcBoParam.setFuncIdList(idList);
        List<AuthUserFunc> authUserFuncList = selUserFuncListByParam(funcBoParam);
        if (CollectionUtils.isEmpty(authUserFuncList)) {
            return null;
        }
        List<String> authBoIdList = authUserFuncList.stream().map(a -> a.getAuthBoId()).distinct().collect(Collectors.toList());
        return authBoIdList;
    }

    /**
     * 根据参数查询用户的功能
     *
     * @param userFuncBo
     * @return java.util.List<com.nxin.middle.basic.auth.domain.AuthUserFuncBo>
     * @author 
     * @date 16:44 2019/4/25
     */
    @Override
    public List<AuthUserFunc> selUserFuncListByParam(AuthUserFuncBo userFuncBo) {
        if (userFuncBo == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        AuthUserFuncExample example = new AuthUserFuncExample();
        AuthUserFuncExample.Criteria criteria = example.createCriteria();
        criteria.andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED_VAL);
        if (userFuncBo.getBoId() != null) {
            criteria.andBoIdEqualTo(userFuncBo.getBoId());
        }
        if (userFuncBo.getAuthBoId() != null) {
            criteria.andAuthBoIdEqualTo(userFuncBo.getAuthBoId());
        }
        if (StringCheckDsUtil.isNotBlank(userFuncBo.getBusId())) {
            criteria.andBusIdEqualTo(userFuncBo.getBusId());
        }
        if (StringCheckDsUtil.isNotBlank(userFuncBo.getBusType())) {
            criteria.andBusTypeEqualTo(userFuncBo.getBusType());
        }
        if (userFuncBo.getSystemId() != null) {
            criteria.andSystemIdEqualTo(userFuncBo.getSystemId());
        }
        if (userFuncBo.getSubSystemId() != null) {
            criteria.andSubSystemIdEqualTo(userFuncBo.getSubSystemId());
        }
        if (CollectionUtils.isNotEmpty(userFuncBo.getFuncIdList())) {
            criteria.andFuncIdIn(userFuncBo.getFuncIdList());
        }
        List<AuthUserFunc> authUserFuncList = authUserFuncMapper.selectByExample(example);

        return authUserFuncList;
    }

    /**
     * 根据参数查询用户的功能（关联功能表）
     *
     * @return java.util.List<com.nxin.middle.basic.auth.dao.model.AuthUserFunc>
     * @author 
     * @date 18:44 8/15
     **/
    @Override
    public List<AuthUserFuncBo> selUserFuncWithFuncListByParam(AuthUserFuncBo userFuncBo) {
        if (userFuncBo == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        log.info("++++人员权限入参{}",userFuncBo);
        List<AuthUserFuncBo> userFuncBoList = authUserFuncExMapper.selUserFuncList(userFuncBo);
        return userFuncBoList;
    }

    /**
     * 根据参数删除用户的功能
     *
     * @return java.util.List<com.nxin.middle.basic.auth.dao.model.AuthUserFunc>
     * @author 
     * @date 18:44 8/15
     **/
    @Override
    public int delUserFuncByParam(AuthUserFunc userFunc) {
        log.info("==========删除条件==========" + userFunc);
        if (userFunc == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        AuthUserFuncExample example = new AuthUserFuncExample();
        AuthUserFuncExample.Criteria criteria = example.createCriteria();
        criteria.andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED_VAL);
        if (userFunc.getFuncId() != null) {
            criteria.andFuncIdEqualTo(userFunc.getFuncId());
        }
        if (userFunc.getBoId() != null) {
            criteria.andBoIdEqualTo(userFunc.getBoId());
        }
        if (userFunc.getAuthBoId() != null) {
            criteria.andAuthBoIdEqualTo(userFunc.getAuthBoId());
        }

        if (!StringCheckDsUtil.isBlank(userFunc.getBusId())) {
            criteria.andBusIdEqualTo(userFunc.getBusId());
        }
        if (!StringCheckDsUtil.isBlank(userFunc.getBusType())) {
            criteria.andBusTypeEqualTo(userFunc.getBusType());
        }
        if (userFunc.getSystemId() != null) {
            criteria.andSystemIdEqualTo(userFunc.getSystemId());
        }
        if (userFunc.getSubSystemId() != null) {
            criteria.andSubSystemIdEqualTo(userFunc.getSubSystemId());
        }
        AuthUserFunc func = new AuthUserFunc();
        func.setIsEnabled(CommonDsConstant.IS_NOT_ENABLED_VAL);
        int result = authUserFuncMapper.updateByExampleSelective(func, example);
        if (result <= 0) {
//            throw new ServerServiceException(Errors.SYSTEM_DELETE_ERROR);
        }
        return result;
    }

    /**
     * 增加用户功能(删除历史数据)
     *
     * @param userFuncBo
     * @return void
     * @author 
     * @date 9:13 8/15
     **/
    @Override
    public void addUserFuncs(AuthUserFuncBo userFuncBo) {
        log.info("==========增加内容==========" + userFuncBo);
        if (userFuncBo == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        String boId = userFuncBo.getBoId();
        String funcIds = userFuncBo.getFuncIds();
        String busId = userFuncBo.getBusId();
        String busType = userFuncBo.getBusType();
        String authBoId = userFuncBo.getAuthBoId();
        if (boId == null || StringCheckDsUtil.isBlank(funcIds)
                || StringCheckDsUtil.isBlank(busId) || StringCheckDsUtil.isBlank(busType)
                || authBoId == null
        ) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        String[] funcIdStrs = funcIds.split(CommonDsConstant.DELIMITER_SG_ZY);
        if (funcIdStrs.length <= 0) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }

        // 查询是否存在，如果存在，删除
        AuthUserFuncBo param = new AuthUserFuncBo();
        param.setBoId(boId);
        param.setAuthBoId(authBoId);
//        param.setBusId(busId);
//        param.setBusType(busType);
        Short systemId = userFuncBo.getSystemId();
        if (systemId != null) {
            param.setSystemId(systemId);
        }
        List<AuthUserFunc> userFuncList = selUserFuncListByParam(param);
        if (!CollectionUtils.isEmpty(userFuncList)) {
            delUserFuncByParam(param);
        }
        List<Long> fundIdList = new ArrayList<>();
        for (String funcIdStr : funcIdStrs) {
            Long funcId = Long.valueOf(funcIdStr);
            fundIdList.add(funcId);
        }
        AuthFuncBo funcBo = new AuthFuncBo();
        funcBo.setFuncIdList(fundIdList);
        funcBo.setIsEnabled(CommonDsConstant.IS_ENABLED_VAL);
        List<AuthFunc> funcList = authFuncService.selFuncListByParam(funcBo);
        if (CollectionUtils.isEmpty(funcList)) {
            return;
        }
        List<AuthUserFunc> userFuncArrayList = new ArrayList<>();
        for (AuthFunc func : funcList) {
            AuthUserFunc userFunc = null;
            userFunc = new AuthUserFunc();
            userFunc.setBoId(boId);
            userFunc.setFuncId(func.getId());
            userFunc.setSubSystemId(func.getSubSystemId());
            userFunc.setSystemId(func.getSystemId());
            userFunc.setBusId(busId);
            userFunc.setBusType(busType);
            userFunc.setAuthBoId(authBoId);
            userFuncArrayList.add(userFunc);
        }
        log.info("listSize={}", userFuncArrayList.size());
        int i = authUserFuncExMapper.insertUserFuncList(userFuncArrayList);
        log.info("i={}", i);
        if (i < userFuncArrayList.size()) {
//            throw new ServerServiceException(Errors.SYSTEM_INSERT_ERROR);
        }
    }

    /**
     * 增加用户该系统下的所有功能
     *
     * @param userFuncBo
     * @return void
     * @author 
     * @date 10:30 2019/4/8
     */
    @Override
    public void addUserFuncsBySysId(AuthUserFuncBo userFuncBo) {
        log.info("==========增加内容==========" + userFuncBo);
        if (userFuncBo == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        String boId = userFuncBo.getBoId();
        Short systemId = userFuncBo.getSystemId();
        if (boId == null || systemId == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        // 查询是否存在，如果存在，删除
        AuthUserFuncBo param = new AuthUserFuncBo();
        param.setBoId(boId);
        param.setBusId(boId);
        param.setBusType("MEMBER");
        param.setSystemId(systemId);
        List<AuthUserFunc> userFuncList = selUserFuncListByParam(param);
        if (!CollectionUtils.isEmpty(userFuncList)) {
            delUserFuncByParam(param);
        }
        AuthFuncBo funcBo = new AuthFuncBo();
        funcBo.setSystemId(systemId);
        List<AuthFunc> authFuncList = authFuncService.selFuncListByParam(funcBo);
        if (CollectionUtils.isEmpty(authFuncList)) {
            return;
        }
        List<AuthUserFunc> authUserFuncList = new ArrayList<>();
        for (AuthFunc authFunc : authFuncList) {
            AuthUserFunc userFunc = new AuthUserFunc();
            userFunc.setBoId(boId);
            userFunc.setFuncId(authFunc.getId());
            userFunc.setSubSystemId(authFunc.getSubSystemId());
            userFunc.setSystemId(authFunc.getSystemId());
            userFunc.setBusId(boId);
            userFunc.setBusType("MEMBER");
            authUserFuncList.add(userFunc);
        }
        log.info("listSize={}", authFuncList.size());
        int i = authUserFuncExMapper.insertUserFuncList(authUserFuncList);
        log.info("i={}", i);
        if (i < authFuncList.size()) {
//            throw new ServerServiceException(Errors.SYSTEM_INSERT_ERROR);
        }
    }

    /**
     * 查询用户是否授权当前功能（若非末级节点则连带查询子孙节点）
     *
     * @param authUserFuncBo
     * @return
     * @author LS
     * @date 13:12 2020/3/20
     */
    @Override
    public AuthFuncBo selSpecUserFunc(AuthUserFuncBo authUserFuncBo) {
        AuthFunc func = authFuncMapper.selectByPrimaryKey(authUserFuncBo.getFuncId());
        if (func == null) {
            return null;
        }
        AuthFuncBo funcBo = BeanCopierDsUtil.copyProperties(func, AuthFuncBo.class);
        if (authUserFuncBo.getBoId().equals(authUserFuncBo.getAuthBoId())) {
            return funcBo;
        }
        AuthUserFuncExample example = new AuthUserFuncExample();
        AuthUserFuncExample.Criteria criteria = example.createCriteria();
        criteria.andAuthBoIdEqualTo(authUserFuncBo.getAuthBoId());
        criteria.andBoIdEqualTo(authUserFuncBo.getBoId());
        criteria.andFuncIdEqualTo(authUserFuncBo.getFuncId());
        criteria.andSystemIdEqualTo(authUserFuncBo.getSystemId());
        criteria.andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED_VAL);
        List<AuthUserFunc> userFuncList = authUserFuncMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(userFuncList)) {
            return funcBo;
        }
        //查询其子孙节点是否分配权限，如是返回功能，否则返回空
        AuthFuncExample funcExample = new AuthFuncExample();
        AuthFuncExample.Criteria funcCriteria = funcExample.createCriteria();
        funcCriteria.andAxisLike(func.getAxis() + "%");
        funcCriteria.andSystemIdEqualTo(authUserFuncBo.getSystemId());
        List<AuthFunc> funcList = authFuncMapper.selectByExample(funcExample);
        List<Long> funcIdList = funcList.stream().map(AuthFunc::getId).collect(Collectors.toList());
        example = new AuthUserFuncExample();
        criteria = example.createCriteria();
        criteria.andAuthBoIdEqualTo(authUserFuncBo.getAuthBoId());
        criteria.andBoIdEqualTo(authUserFuncBo.getBoId());
        criteria.andFuncIdIn(funcIdList);
        criteria.andSystemIdEqualTo(authUserFuncBo.getSystemId());
        criteria.andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED_VAL);
        userFuncList = authUserFuncMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(userFuncList)) {
            return funcBo;
        }
        return null;
    }
}
